package com.util
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.net.URLRequest;
	
	import mx.controls.Image;
	
	/*last update 2009.6.16. by red.
	role : 이미지를  사이즈에 맞게  로딩 후, 이벤트 보냄.
	*/
		 
	//[Event(name="snapsMyImageLoadComplete", type="snpas.SnapsEvent")]	
	public final class myImage extends Image
	{	
		private var imageLoader:Loader = new Loader();
		
		
    	public function myImage(src:String=null) {
    		if(src)
    			loadImage(src);
		}
		
		public function loadImage(src:String):void {
			var request:URLRequest = new URLRequest(src);
			imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, image_completeHandler);
			imageLoader.load(request);
		}
		
		private function image_completeHandler(event:Event):void{
			var bmd:BitmapData = Bitmap(event.currentTarget.content).bitmapData;
			
			var originalWidth:uint = bmd.width;
			var originalHeight:uint = bmd.height;
			var newWidth:uint = width;
			var newHeight:uint = height;
			
			try {
	
				if(originalWidth > newWidth || originalHeight > newHeight)
				{
					var m:Matrix = new Matrix();
					var scaleX:Number = 1;
					var scaleY:Number = 1;
					var scale:Number = 1;
					var sx:Number = newWidth / originalWidth;
					var sy:Number = newHeight / originalHeight;
					scale = Math.min(sx, sy);
					newWidth = originalWidth * scale;
					newHeight = originalHeight * scale;
					m.scale(scale, scale);
					
					if(newWidth == 0) newWidth = 1;
					if(newHeight == 0) newHeight = 1;
				
				
					var newbmd:BitmapData = new BitmapData(newWidth, newHeight);
					newbmd.draw(bmd, m);
					source = new Bitmap(newbmd);
					
					//dispatchEvent( new SnapsEvent(SnapsEvent.SNAPS_MYIMAGE_LOAD_COMPLETE) );				
				}
				else
				{
					source = new Bitmap(bmd);
					
					//dispatchEvent( new SnapsEvent(SnapsEvent.SNAPS_MYIMAGE_LOAD_COMPLETE) );	
				}
			}catch (e:Error) {
			 trace("@@@@@@@@@@ 이미지 스무싱 오류 ");	
			}			
			imageLoader.unload();
		}
			
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			if(content is Bitmap)
			{
				var bmp:Bitmap = Bitmap(content);
				if(bmp)
				{
					bmp.smoothing = true;
				}
			}
		}
		
		public function setSmoonth():void {
			if(content is Bitmap)
			{
				var bmp:Bitmap = Bitmap(content);
				if(bmp && bmp.smoothing == false)
				{
					bmp.smoothing = true;
				}
			}			
		}
	}
}